<?php


namespace App\Http\service;
use App\Exceptions\ApiException;
use App\Models\Sys as SysModel;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;

class DyService
{
    private $url="https://developer.toutiao.com/";
    private $appid="";
    private $secret="";
    private $access_token="";

    public function __construct()
    {
        $this->appid=SysModel::getValue("dy_appid");
        $this->secret=SysModel::getValue("dy_secret");
        $this->access_token=Cache::get("dy_access_token");
        if (!$this->access_token){
            $this->getAccessToken();
        }
    }
    //同一套代码如何在不同平台运行不同模块代码
    private function getAccessToken()
    {
        $url=$this->url."api/apps/v2/token";
        $data=[
            "appid"=>$this->appid,
            'secret'=>$this->secret,
            "grant_type"=>"client_credential"
        ];
        $res=Http::post($url,$data)->json();
        if ($res["err_no"]!=0){
            throw new ApiException($res["err_tips"]);
        }
        $access_token=$res["data"]["access_token"];
        Cache::put("dy_access_token",$access_token,$res["data"]["expires_in"]);
        $this->access_token=$access_token;
    }

    public function code2Session($code,$anonymous_code)
    {
        $url=$this->url."api/apps/v2/jscode2session";
        $data=[
            "appid"=>$this->appid,
            "secret"=>$this->secret,
            "code"=>$code,
            "anonymous_code"=>$anonymous_code
        ];
        $res=Http::post($url,$data)->json();
        if($res["err_no"]!=0){
            throw new ApiException($res["err_tips"]);
        }
        return $res["data"];

    }

    public function getPhone($encryptedData,$iv,$session){

        try {
            $phone = openssl_decrypt(base64_decode($encryptedData,true), 'AES-128-CBC', base64_decode($session), OPENSSL_RAW_DATA, base64_decode($iv));
            $phone=json_decode($phone,true);
            return $phone;
        }catch (\Exception $exception){
            throw new ApiException($exception->getMessage());
        }


    }
}
